package cn.hchaojie.camp.week2.qa;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DemoCP3 {
	public static void main(String[] args) {
		Factory f = new Factory();
		
		ExecutorService executor = Executors.newFixedThreadPool(2);
		executor.execute(new Producer(f));
		executor.execute(new Consumer(f));
		
		executor.shutdown();
	}
	
	static class Producer implements Runnable {
		Factory factory;
		public Producer(Factory f) {
			this.factory = f;
		}

		@Override
		public void run() {
			try {
				while (true) {
					Thread.sleep((long) (Math.random() * 1000 + 500));
					factory.put();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	static class Consumer implements Runnable {
		Factory factory;
		public Consumer(Factory f) {
			this.factory = f;
		}

		@Override
		public void run() {
			try {
				while (true) {
					Thread.sleep((long) (Math.random() * 1000 ));
					factory.take();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	static class Factory {
		private static final int MAX = 10;
		private List<Integer> eggs = new ArrayList<>();

		private int id = 1;
		
		public synchronized void put() {
			if (eggs.size() >= MAX) {
				try {
					System.out.println("MD, 放不下了。。。我再等等，总会有人买走鸡蛋的。。！");
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} 

			System.out.println("哈哈， 卖出去了。#" + id);
			eggs.add(id++);
			
			System.out.println("有鸡蛋咯！等着买的快来看哦！");
			notify();
		}
		
		public synchronized void take() {
			if (eggs.size() <= 0) {
				try {
					System.out.println("MD，卖完了。。。再等等看看一会儿有没有人卖！");
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			Integer id = eggs.remove(eggs.size() - 1);
			System.err.println("嘿嘿，买到了 #" + id);
			
			System.out.println("蛋农！可以加鸡蛋了。。。");
			notify();
		}
	}
}
